package fs

import (
	"path/filepath"
)

type pathList struct {
	path string
	next *pathList
}

func Entries(c <-chan Fs) (<-chan Entry, error) {
	sc := make(chan Entry)
	go entries(sc, c)
	return sc, nil
}

func entries(sc chan<- Entry, c <-chan Fs) {
	indent := 0
	var paths *pathList
	var path string
	for fs := range c {
		if fs.Info != nil {
			var p string
			depth := indent
			if fs.Info.IsDir() {
				paths = &pathList{path, paths}
				if indent == 0 {
					// first directory holds full path
					path = fs.Info.Name()
				} else {
					path = filepath.Join(path, fs.Info.Name())
				}
				indent++
				fs.Reply <- Down
				p = path
			} else {
				p = filepath.Join(path, fs.Info.Name())
				fs.Reply <- Next
			}
			sc <- Entry{Info: fs.Info, Path: p, Depth: depth}
		} else {
			fs.Reply <- Next
			if fs.Info == nil && fs.Data == nil {
				if indent--; indent == 0 {
					break
				}
				path, paths = paths.path, paths.next
			}
		}
	}
	close(sc)
}
